﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

namespace WcfContrib.Helpers
{
    static class ConfigurationHelper
    {
        internal static bool TryGetValue<T>(string keyName, out T value)
        {
            value = default(T);

            string setting = ConfigurationManager.AppSettings[keyName];

            if (setting == null)
            {
                return false;
            }

            try
            {
                value = (T)Convert.ChangeType(setting, typeof(T));
            }
            catch
            {
                return false;
            }

            return true;
        }

        internal static T GetValue<T>(string keyName)
        {
            return GetValue(keyName, default(T));
        }

        internal static T GetValue<T>(string keyName, T defaultValue)
        {
            T value;
            if (TryGetValue<T>(keyName, out value))
            {
                if (value is string && value.ToString() == string.Empty)
                {
                    return defaultValue;
                }

                return value;
            }

            return defaultValue;
        }
    }
}
